package com.power.bank.utils;

import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Map;


@Component
public class WeiXinUtils {
    String urlStr = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";

    @Autowired
    WeiXinConfig weiXinConfig;

    RestTemplate restTemplate = new RestTemplate();

    public JSONObject getOpenId(String code) {
        urlStr = urlStr.replace("APPID", weiXinConfig.getAppId())
                .replace("SECRET", weiXinConfig.getAppSecret())
                .replace("JSCODE", code);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON); // 设置Content-Type为application/json

        // 构建请求实体
        HttpEntity<String> entity = new HttpEntity<>(null, headers);

        // 发起GET请求
        String  response = restTemplate.exchange(urlStr, HttpMethod.GET, entity,String.class).getBody();

        System.out.println(urlStr);
        System.out.println(response);

        return JSONObject.parseObject(response);
    }
}
